var LIVE = {
 url: function(url) {
   return basePath + url;
 },
 date: {
  init: function() {
    Date.prototype.Format = function (fmt) { //author: meizz
      var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
      };
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
      return fmt;
    }
  },
  now: function() {
    return new Date() - 0;
  }
},
 table: {
   init: function() {
     var dCheckAll = $('table.table > thead input:checkbox[data-check-all="true"]');
     if (dCheckAll.length) {
       dCheckAll.click(function(e) {
         LIVE.table.select(dCheckAll.closest('table.table').find('input:checkbox:gt(0)'), this.checked);
       });
     }
     $('table.table.table-rowclick[data-rowclick-callback]').each(function(index, table) {
       var callback = $(this).attr('data-rowclick-callback');
       $(table).children('tbody').delegate('tr[data-id]', 'click', function(e) {
         if (typeof window[callback] !== 'function') {
           return;
         }
         var tagName = e.target.tagName.toUpperCase(), dTarget = $(e.target);
         if (tagName == 'A' && dTarget.hasClass('modal-confirm')) {
           return;
         }
         e.stopPropagation();
         if ((tagName == 'A' && !dTarget.hasClass('btn-rowclick')) || tagName == 'LABEL' || tagName == 'INPUT') {
           return;
         }
         var id = $(this).attr('data-id');
         if (id) {
           window[callback](id);
         }
       });
     });

    $('.allCheckbox').on('click' , function(){
      var that = this;
      $(this).closest('table').find('tr > td:first-child input:checkbox').each(function(){
        !this.disabled && (this.checked = that.checked);
      });
    });
   }
 },
 component: {
   init: function() {
     // bootstrap
     $('#bd').delegate('a.btn[data-loading-text], button.btn[data-loading-text]', 'click', function(e) {
       $(this).button('loading');
     });
     LIVE.component.editable.init();
   },
   editable: {
     init: function() {
      $.fn.editable.defaults.mode = 'inline';
      $.fn.editableform.loading = "<div class='editableform-loading'><i class='light-blue icon-2x icon-spinner icon-spin'></i></div>";
      $.fn.editableform.buttons = '<button type="submit" class="btn btn-info editable-submit"><i class="icon-ok icon-white"></i></button>'+
        '<button type="button" class="btn editable-cancel"><i class="icon-remove"></i></button>';
     }

   },
   select2: {
    config: function(config) {
      return $.extend(true, $.fn.select2.defaults, {
        ajax: {
          dataType: 'json',
          delay: 500,
          cache: true,
        },
        language: {
          searching: function() {
            return '<span class="center"><i class="icon-spinner icon-spin orange bigger-125"></i> 加载中...</span>';
          },
          loadingMore: function() {return '<span class="center"><i class="icon-spinner icon-spin orange bigger-125"></i> 加载中...</span>';},
          errorLoading: function() {return '<span class="center"><i class="icon-spinner icon-spin orange bigger-125"></i> 加载中...</span>';},
        },
        escapeMarkup: function (markup) { return markup },
        allowClear: true,
      }, config);
    }
   },
   form: {
     getData: function(element) {
      var results = {};
      $.each(element.serializeArray(), function(i, field) {
        results[field.name] = $.trim(field.value);
      });
      return results;
     },
   }
 },
 dialog: {
   _buildModal: function() {
     var html = [
       '<div class="modal fade" tabindex="-1" role="dialog" style="display:none">',
       '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">',
       '<button type="button" class="close" data-dismiss="modal">×</button><h4 class="modal-title"></h4></div>',
       '<div class="modal-body"></div><div class="modal-footer">',
       '</div></div></div></div>'
     ];
     return $(html.join('')).appendTo('#bd');
   },
   get: function(header, body, footer, width) {
     var dEl = LIVE.dialog._buildModal(), dDialog = dEl.children('div.modal-dialog'),
         dModal = dEl.find('> div.modal-dialog > div.modal-content'),
         dHeader = dModal.find('> div.modal-header > h4'),
         dBody = dModal.find('> div.modal-body'),
         dFooter = dDialog.find('> div.modal-content > div.modal-footer');
     if (header) {
       dHeader.html(header);
     } else {
       dHeader.html('<i class="fa fa-warning"></i> 提示');
     }
     if (body) {
       dBody.html(body);
     }
     if (footer) {
       dFooter.html(footer);
     } else {
       dFooter.html('<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>');
     }
     if (width) {
       dDialog.width(width);
     }
     return dEl;
   },
   init: function() {
     var self = LIVE.dialog;
     // alert
     window.alert = function(content, header, button) {
       button = button || '关闭';
       self.get(header, content, '<button type="button" class="btn btn-default" data-dismiss="modal">' + button + '</button>', 400).modal({ backdrop: 'static' });
     };

     // confirm
     window.confirm = function(content, header, onSubmit, onClose, width) {
      var dConfirm = self.get(header, content, [
        '<a href="javascript:void(0)" class="btn btn-danger">确认</a>',
        '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>'
      ].join(''), width|| 400).modal({ backdrop: 'static' });

      dConfirm.on('click', '.modal-footer > a.btn-danger', (e) =>{
        dConfirm.find('.btn-danger').addClass('disabled');
        dConfirm.find('.btn-danger').text('正在确认...');
         onSubmit(dConfirm);
      });
      dConfirm.on('hidden.bs.modal',  (e) => {
        onClose && onClose();
        dConfirm.off();
        dConfirm.remove();
      });
      return dConfirm;
    };
     var dConfirm = self.get(null, null, [
       '<a href="javascript:void(0)" class="btn btn-danger" data-loading-text="正在确认...">确认</a>',
       '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>'
     ].join(''), 400);
     $('#bd').delegate('a.modal-confirm[data-confirm]', 'click', function(e) {
       e.preventDefault();
       var dModal = dConfirm.find('> div.modal-dialog > div.modal-content');
       dModal.find('> div.modal-body').html($(this).attr('data-confirm'));
       dModal.find('> div.modal-header > h4.modal-title').html($(this).attr('data-title')||'提示');
       dModal.find('> div.modal-footer > a.btn-danger').attr('href', $(this).attr('href'));
       dConfirm.modal({ backdrop: 'static' });
     });
   }
 },
 clipboard: {
   init: function() {
     var dClipboard = $('.btn-clipboard[data-clipboard-element]'), client;
     if (dClipboard.length) {
       $.getScript(LIVE.url('static/blue/lib/zeroclipboard-2.2.0.js'), function() {
         ZeroClipboard.config({ swfPath: LIVE.url('static/blue/lib/ZeroClipboard.swf') });
         client = new ZeroClipboard(dClipboard);
         client.on('ready', function() {
           client.on('copy', function(e) {
             var el = document.getElementById($(e.target).attr('data-clipboard-element')), tag = el.tagName.toUpperCase(), text;
             if (tag == 'INPUT' || tag == 'SELECT' || tag == 'TEXTAREA') {
               text = $(el).val();
             } else {
               text = $(el).text();
             }
             e.clipboardData.setData('text/plain', text);
           });
           client.on('aftercopy', function(e) {
             var dEl = $(e.target);
             if (dEl.attr('data-clipboard-callback')) {
               var callback = window[dEl.attr('data-clipboard-callback')];
               if (typeof callback === 'function') {
                 callback(e);
               }
             }
           });
         });
       });
     }
   }
 },
 util: {
   hasEmpty: function(tager) {
      for (var key in tager) {
        if (!tager[key]) {
          return true;
        }
      }
   },
   pagination: function(count, each, page, url, showinfo) {
     if (count === undefined || each === undefined) {
       return '';
     }
     if (typeof showinfo === 'undefined') {
       showinfo = true;
     }
     count = parseInt(count, 10);
     each = parseInt(each, 10);
     var output = [], pages = Math.ceil(count / each);
     if (count > 0) {
       page = Math.max(Math.min(pages, parseInt(page, 10)), 1);
       output.push('<ul class="pagination">');

       if (showinfo) {
        var offsetStart = (page - 1) * each + 1;
        var offsetEnd = Math.min(offsetStart + each - 1, count);
        output.push('<li class="pagination-info"><span>正在显示 ' + offsetStart + ' ~ ' + offsetEnd + ' 个记录，共 ' + pages + ' 页，' + count + ' 个记录</span></li>');
      }
       if (page == 1) {
         output.push('<li class="disabled"><span><i class="icon-double-angle-left"></i></span></li>');
       } else {
         output.push('<li><a href="' + url.replace(/%page%/g, page - 1) + '" rel="' + (page - 1) + '"><i class="icon-double-angle-left"></i></a></li>');
       }
       var start = page - 2, end = page + 2, i;
       if (start < 1) {
         end = Math.min(pages, end + (1 - start));
         start = 1;
       }
       if (end > pages) {
         start = Math.max(1, start - (end - pages));
         end = pages;
       }
       for (i = start; i <= end; ++i) {
         if (page == i) {
           output.push('<li class="active"><span>' + page + '</span></li>');
         } else {
           output.push('<li><a href="' + url.replace(/%page%/g, i) + '" rel="' + i + '">' + i + '</a></li>');
         }
       }
       if (page == pages) {
         output.push('<li class="disabled"><span><i class="icon-double-angle-right"></i></span></li>');
       } else {
         output.push('<li><a href="' + url.replace(/%page%/g, page + 1) + '" rel="' + (page + 1) + '"><i class="icon-double-angle-right"></i></a></li>');
       }
       output.push('</ul>');

     }
     return output.join('');
   },
   isMobileNumber: function(phone) {
      if((/^1(3|4|5|7|8)\d{9}$/.test(phone))){
        return true;
      }
      return false;
   }
 },
 app: {
   init: function() {

   }
 }
};

(function() {
  LIVE.date.init();
  LIVE.dialog.init();
  LIVE.table.init();
  LIVE.component.init();
})();
